<template>
  <div class="page-container">
    <div class="page-header">
      <div class="header-left">
        <el-button @click="$router.push('/dashboard/work-orders')" link>
          <el-icon><Back /></el-icon> 返回列表
        </el-button>
        <h2>工单详情</h2>
      </div>
      <div class="header-actions">
        <!-- 移除编辑按钮 -->
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>

    <!-- 详情信息 -->
    <div v-else class="detail-wrapper">
      <!-- 基本信息 -->
      <el-card class="detail-card">
        <template #header>
          <div class="card-header">
            <h3>工单信息</h3>
            <div class="card-header-actions">
              <el-button 
                v-if="canUpdateStatus" 
                type="primary" 
                size="small" 
                @click="handleStatusUpdate"
              >
                更新状态
              </el-button>
              <el-button 
                v-if="canAssign" 
                type="primary" 
                size="small" 
                @click="handleAssign"
              >
                分配处理人
              </el-button>
            </div>
          </div>
        </template>
        
        <el-descriptions :column="2" border>
          <el-descriptions-item label="工单编号">{{ workOrderDetail.orderCode }}</el-descriptions-item>
          <el-descriptions-item label="工单标题">{{ workOrderDetail.title }}</el-descriptions-item>
          <el-descriptions-item label="客户名称">{{ workOrderDetail.customerName }}</el-descriptions-item>
          <el-descriptions-item label="关联业务">{{ workOrderDetail.businessName || '无' }}</el-descriptions-item>
          <el-descriptions-item label="工单类型">{{ workOrderDetail.orderType }}</el-descriptions-item>
          <el-descriptions-item label="优先级">
            <span :class="`priority-tag ${getPriorityClass(workOrderDetail.priority)}`">
              {{ workOrderDetail.priority }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="处理人">
            {{ workOrderDetail.assignedEmployeeName || '未分配' }}
          </el-descriptions-item>
          <el-descriptions-item label="工单状态">
            <el-tag :type="getStatusTagType(workOrderDetail.status)">
              {{ workOrderDetail.status }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(workOrderDetail.createdAt) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatDate(workOrderDetail.updatedAt) }}</el-descriptions-item>
          <el-descriptions-item label="问题描述" :span="2">
            <div class="content-text">{{ workOrderDetail.description }}</div>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 处理记录 -->
      <el-card class="detail-card">
        <template #header>
          <div class="card-header">
            <h3>处理记录</h3>
            <el-button type="primary" size="small" @click="handleAddSolution">
              <el-icon><Plus /></el-icon> 添加处理记录
            </el-button>
          </div>
        </template>
        
        <div v-if="solutions.length" class="solutions-list">
          <div v-for="(item, index) in solutions" :key="index" class="solution-item">
            <div class="solution-header">
              <span class="solution-employee">{{ item.operatorName }}</span>
              <span class="solution-time">{{ formatDate(item.createdAt) }}</span>
            </div>
            <div class="solution-content">{{ item.newValue }}</div>
          </div>
        </div>
        
        <el-empty v-else description="暂无处理记录" />
      </el-card>
      
      <!-- 状态更新历史 -->
      <el-card class="detail-card">
        <template #header>
          <div class="card-header">
            <h3>状态更新历史</h3>
          </div>
        </template>
        
        <el-timeline v-if="statusHistory.length">
          <el-timeline-item
            v-for="(item, index) in statusHistory"
            :key="index"
            :timestamp="formatDate(item.createdAt)"
            :type="getStatusTimelineType(item.newValue)"
          >
            <span class="history-content">
              {{ item.content }}
              <span v-if="item.operatorName">（操作人：{{ item.operatorName }}）</span>
            </span>
          </el-timeline-item>
        </el-timeline>
        
        <el-empty v-else description="暂无状态更新记录" />
      </el-card>
    </div>

    <!-- 添加处理记录弹窗 -->
    <el-dialog v-model="solutionDialogVisible" title="添加处理记录" width="500px">
      <el-form :model="solutionForm" ref="solutionFormRef" :rules="solutionFormRules">
        <el-form-item label="处理内容" prop="solution" label-width="80px">
          <el-input 
            v-model="solutionForm.solution" 
            type="textarea" 
            :rows="6"
            placeholder="请输入处理内容"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="solutionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitSolution" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 状态更新弹窗 -->
    <el-dialog v-model="statusDialogVisible" title="更新工单状态" width="400px">
      <el-form :model="statusForm" ref="statusFormRef" :rules="statusFormRules">
        <el-form-item label="工单状态" prop="status" label-width="80px">
          <el-select v-model="statusForm.status" placeholder="请选择状态">
            <el-option label="待处理" value="待处理" />
            <el-option label="处理中" value="处理中" />
            <el-option label="待回单" value="待回单" />
            <el-option label="已完成" value="已完成" />
            <el-option label="已关闭" value="已关闭" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="statusDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitStatusUpdate" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 分配处理人弹窗 -->
    <el-dialog v-model="assignDialogVisible" title="分配处理人" width="400px">
      <el-form :model="assignForm" ref="assignFormRef" :rules="assignFormRules">
        <el-form-item label="处理人" prop="assignedTo" label-width="80px">
          <el-select 
            v-model="assignForm.assignedTo" 
            placeholder="请选择处理人"
            filterable
          >
            <el-option 
              v-for="item in employeeOptions" 
              :key="item.id" 
              :label="item.realName" 
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="assignDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAssign" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { 
  getWorkOrder, 
  updateWorkOrderStatus, 
  assignWorkOrder,
  addWorkOrderSolution,
  getWorkOrderSolutions,
  getWorkOrderStatusHistory
} from '@/api/workOrders';
import { getEmployees } from '@/api/employees';
import { useUserStore } from '@/stores/user';
import { ElMessage } from 'element-plus';
import dayjs from 'dayjs';

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();

// 响应式数据
const workOrderId = ref(null);
const workOrderDetail = ref({});
const solutions = ref([]);
const statusHistory = ref([]);
const loading = ref(true);
const submitLoading = ref(false);
const employeeOptions = ref([]);

// 弹窗状态
const solutionDialogVisible = ref(false);
const statusDialogVisible = ref(false);
const assignDialogVisible = ref(false);

// 表单数据
const solutionForm = reactive({
  solution: ''
});

const statusForm = reactive({
  status: ''
});

const assignForm = reactive({
  assignedTo: null
});

// 表单验证规则
const solutionFormRules = {
  solution: [
    { required: true, message: '请输入处理内容', trigger: 'blur' }
  ]
};

const statusFormRules = {
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
};

const assignFormRules = {
  assignedTo: [
    { required: true, message: '请选择处理人', trigger: 'change' }
  ]
};

// 表单引用
const solutionFormRef = ref();
const statusFormRef = ref();
const assignFormRef = ref();

// 计算属性 - 是否可以更新状态
const canUpdateStatus = computed(() => {
  const currentUserRole = userStore.userInfo?.role;
  return currentUserRole === 'admin' || 
    currentUserRole === 'manager' || 
    workOrderDetail.value.assignedTo === userStore.userInfo?.id;
});

// 计算属性 - 是否可以分配处理人
const canAssign = computed(() => {
  const currentUserRole = userStore.userInfo?.role;
  return currentUserRole === 'admin' || currentUserRole === 'manager';
});

// 获取工单详情
const getWorkOrderDetail = async () => {
  try {
    loading.value = true;
    const response = await getWorkOrder(workOrderId.value);
    if (response.code === 200) {
      workOrderDetail.value = response.data;
    }
  } catch (error) {
    console.error('获取工单详情失败:', error);
    ElMessage.error('获取工单详情失败');
  } finally {
    loading.value = false;
  }
};

// 获取处理记录
const getWorkOrderSolutionList = async () => {
  try {
    const response = await getWorkOrderSolutions(workOrderId.value);
    if (response.code === 200) {
      solutions.value = response.data || [];
    }
  } catch (error) {
    console.error('获取处理记录失败:', error);
    ElMessage.error('获取处理记录失败');
  }
};

// 获取状态历史记录
const getStatusHistoryList = async () => {
  try {
    const response = await getWorkOrderStatusHistory(workOrderId.value);
    if (response.code === 200) {
      statusHistory.value = response.data || [];
    }
  } catch (error) {
    console.error('获取状态历史记录失败:', error);
    ElMessage.error('获取状态历史记录失败');
  }
};

// 获取员工选项
const getEmployeeOptions = async () => {
  try {
    const response = await getEmployees({ size: 1000 });
    console.log('员工API响应:', response);
    if (response.code === 200) {
      console.log('员工数据结构:', response.data);
      employeeOptions.value = response.data.data || [];
      console.log('设置的员工选项:', employeeOptions.value);
    }
  } catch (error) {
    console.error('获取员工列表失败:', error);
    ElMessage.error('获取员工列表失败');
  }
};

// 格式化日期
const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
};

// 获取状态标签类型
const getStatusTagType = (status) => {
  const statusMap = {
    '待处理': 'info',
    '处理中': 'primary',
    '待回单': 'warning',
    '已完成': 'success',
    '已关闭': 'info'
  };
  return statusMap[status] || 'info';
};

// 获取状态时间线类型
const getStatusTimelineType = (status) => {
  const statusMap = {
    '待处理': 'info',
    '处理中': 'primary',
    '待回单': 'warning',
    '已完成': 'success',
    '已关闭': 'info'
  };
  return statusMap[status] || '';
};

// 获取优先级样式类
const getPriorityClass = (priority) => {
  const priorityMap = {
    '低': 'low',
    '中': 'medium', 
    '高': 'high',
    '紧急': 'urgent'
  };
  return priorityMap[priority] || 'medium';
};

// 添加处理记录
const handleAddSolution = () => {
  solutionForm.solution = '';
  solutionDialogVisible.value = true;
};

// 提交处理记录
const submitSolution = async () => {
  try {
    await solutionFormRef.value.validate();
    
    submitLoading.value = true;
    await addWorkOrderSolution(workOrderId.value, solutionForm.solution);
    
    ElMessage.success('添加处理记录成功');
    solutionDialogVisible.value = false;
    
    // 重新获取处理记录列表
    getWorkOrderSolutionList();
  } catch (error) {
    console.error('添加处理记录失败:', error);
    ElMessage.error('添加处理记录失败');
  } finally {
    submitLoading.value = false;
  }
};

// 更新状态
const handleStatusUpdate = () => {
  statusForm.status = workOrderDetail.value.status;
  statusDialogVisible.value = true;
};

// 提交状态更新
const submitStatusUpdate = async () => {
  try {
    await statusFormRef.value.validate();
    
    // 如果状态没变，直接关闭弹窗
    if (statusForm.status === workOrderDetail.value.status) {
      statusDialogVisible.value = false;
      return;
    }
    
    submitLoading.value = true;
    await updateWorkOrderStatus(workOrderId.value, statusForm.status);
    
    ElMessage.success('工单状态更新成功');
    statusDialogVisible.value = false;
    
    // 重新获取工单详情和状态历史
    getWorkOrderDetail();
    getStatusHistoryList();
  } catch (error) {
    console.error('更新工单状态失败:', error);
    ElMessage.error('更新工单状态失败');
  } finally {
    submitLoading.value = false;
  }
};

// 分配处理人
const handleAssign = async () => {
  console.log('当前工单处理人ID:', workOrderDetail.value.assignedTo);
  console.log('当前工单处理人姓名:', workOrderDetail.value.assignedEmployeeName);
  
  assignForm.assignedTo = workOrderDetail.value.assignedTo || null;
  await getEmployeeOptions();
  
  console.log('员工选项:', employeeOptions.value);
  console.log('设置的assignedTo值:', assignForm.assignedTo);
  
  assignDialogVisible.value = true;
};

// 提交分配
const submitAssign = async () => {
  try {
    await assignFormRef.value.validate();
    
    // 如果分配人没变，直接关闭弹窗
    if (assignForm.assignedTo === workOrderDetail.value.assignedTo) {
      assignDialogVisible.value = false;
      return;
    }
    
    submitLoading.value = true;
    await assignWorkOrder(workOrderId.value, assignForm.assignedTo);
    
    ElMessage.success('工单分配成功');
    assignDialogVisible.value = false;
    
    // 重新获取工单详情和状态历史
    getWorkOrderDetail();
    getStatusHistoryList();
  } catch (error) {
    console.error('分配工单失败:', error);
    ElMessage.error('分配工单失败');
  } finally {
    submitLoading.value = false;
  }
};

onMounted(async () => {
  workOrderId.value = route.params.id;
  
  await getWorkOrderDetail();
  getWorkOrderSolutionList();
  getStatusHistoryList();
});
</script>

<style lang="scss" scoped>
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  .header-left {
    display: flex;
    align-items: center;
    
    h2 {
      font-size: 24px;
      font-weight: 600;
      color: #333;
      margin: 0;
      margin-left: 8px;
    }
  }
}

.loading-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
}

.detail-wrapper {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.detail-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    h3 {
      font-size: 18px;
      font-weight: 600;
      margin: 0;
    }
    
    .card-header-actions {
      display: flex;
      gap: 10px;
    }
  }
}

.content-text {
  white-space: pre-line;
  line-height: 1.6;
}

.solutions-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  
  .solution-item {
    border-bottom: 1px solid #eee;
    padding-bottom: 16px;
    
    &:last-child {
      border-bottom: none;
      padding-bottom: 0;
    }
    
    .solution-header {
      display: flex;
      justify-content: space-between;
      margin-bottom: 8px;
      
      .solution-employee {
        font-weight: 600;
        color: #333;
      }
      
      .solution-time {
        color: #999;
        font-size: 13px;
      }
    }
    
    .solution-content {
      white-space: pre-line;
      line-height: 1.6;
    }
  }
}

.history-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

// 优先级标签样式
:deep(.priority-tag) {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  
  &.low {
    background-color: #e1f3d8;
    color: #67c23a;
  }
  
  &.medium {
    background-color: #fdf6ec;
    color: #e6a23c;
  }
  
  &.high {
    background-color: #fef0f0;
    color: #f56c6c;
  }
  
  &.urgent {
    background-color: #f56c6c;
    color: white;
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}
</style> 